#!/bin/bash

echoerr() { echo "$@" 1>&2; }

opts=
opts2="$@"

# examine cwd if nothing was specified.
# if [ -z "$opts2" ]; then
#   opts2="."
# fi

# if colorization wasn't disabled, then add it.
if [ -z "$(printf "%s" "$opts2" | flags \\-n)" ]; then
  opts="$opts -C"
fi

# cat <<EOF
# tree $opts $opts2
# EOF

# don't use -F, breaks grep

# cat <<EOF
# tree -l -D -h -i -f --ignore-case --noreport --dirsfirst --timefmt "%Y-%m-%d %T" $opts "$@"
# EOF

tree -a -l -D -h -i -f --ignore-case --noreport --dirsfirst --timefmt "%Y-%m-%d %T" $opts "$@" \
  `# skip the first line, since it's always "."` \
  | skip-n-lines 1 \
  `# tree surrounds the first column with square brackets. Strip these, for easier parsing later on.` \
  | resub '\[ (.*?) \] (.*)' '\1\2'

# We're done!
exit 0

# The rest of this file was my previous solution (before Feb 25 2022).
# Rather than delete it, I'll leave it here as a no-op.  (I like
# re-reading my old solutions, if only to be reminded of what didn't
# work!)

read -r -d '' output <<EOF
`tree -a -l -D -h -i -f --ignore-case --noreport --dirsfirst --timefmt "%Y-%m-%d %T" $opts "$@"`
EOF

# WARNING: HAX.
printf "%s" "$output" | contains '.* error [\s] opening [\s] dir .*'
status=$?
if [ $status -gt 0 ]; then
  #echo "status $status"
  #echo "output $output"
  1>&2 printf "%s\n" "$(echo "$output" | igrep 'error opening')"
  exit $status
else
# END HAX.

  # the resub is to get rid of the pesky [ ] from tree's output, to make
  # sorting easier

  # the second resub is to remove lines which don't contain numbers,
  # since tree insists on printing each directory name.
  # Actually, forget the second resub.  Just never give lltree more
  # than one path.


  printf "%s\n" "$output" | skip-n-lines 1 | resub '\[ (.*?) \] (.*)' '\1\2' \
    #| cols 0 ,1:3 ,3: | resub '[^/]+ NIL [^/]+' ''
fi

